import type { Router, RouteRecordRaw } from "vue-router"

import { PageEnum } from "/@/enums/pageEnum"
import { useIam } from "/@/hooks/web/useIam"
import { useUserStoreWithOut } from "/@/store/modules/user"
const LOGIN_PATH = PageEnum.BASE_LOGIN
const OAUTH_CALLBACK = PageEnum.OAUTH_CALLBACK
const whitePathList: PageEnum[] = [LOGIN_PATH, OAUTH_CALLBACK]

export async function createWorkspaceGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStoreWithOut()

    console.log('WorkspaceGuard', to.fullPath, to.query)
    // next()
    if (whitePathList.filter((e) => to.path.startsWith(e))?.length > 0) {
      next()
      return
    }
    if (to.query.tenantId && to.query.appId) {
      next()
      return
    }

    const toQuery = JSON.parse(JSON.stringify(to.query))
    // toQuery.tenantId = from.query.tenantId
    // toQuery.appId = from.query.appId
    toQuery.tenantId = useIam().getTenantId()
    toQuery.appId = useIam().getAppId()
    if (!toQuery.tenantId || !toQuery.appId) {
      next()
      return
    }
    next({ path: to.path, query: toQuery })
  })
}
